package com.gejia.qixishare.utils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileReadWriteUtils {

    public static int getFileLineNumber(String filePath) throws IOException {
        LineNumberReader reader = null;
        FileReader in = new FileReader(filePath);
        reader = new LineNumberReader(in);
        long totalLine = Files.lines(Paths.get(filePath)).count();
        closeResource(in, reader);
        return (int)totalLine;
    }

    /**
     * 读取文件指定行数(读取一行)
     * @param filePath 路径
     * @param lineNumber 行号
     */
    public static String readFileAtLineNumber(String filePath, int lineNumber){
        String appointedLine = "";
        FileReader in = null;
        LineNumberReader reader = null;
        try {
            in = new FileReader(filePath);
            reader = new LineNumberReader(in);
            long totalLine = Files.lines(Paths.get(filePath)).count();
            if(lineNumber < 0 || lineNumber > totalLine){
                return "指定行【"+lineNumber+"】不在文件行数范围内";
            }
            int line = 1;
            reader.setLineNumber(lineNumber);
            long i = reader.getLineNumber();
            String s = "";
            while((s = reader.readLine()) != null){
                if(i == line){
                    appointedLine = s;
                    break;
                }
                line++;
            }
            return appointedLine;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(in, reader);
        }
        return appointedLine;
    }

    /**
     * 关闭资源
     * @param in
     * @param reader
     */
    public static  void closeResource(FileReader in,LineNumberReader reader){
        try {
            if(reader != null){
                reader.close();
            }
            if(in != null){
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
